<template>
    <div style="height: 100%">
        <el-card style="height: 8%">
            <el-row align="right" :gutter="10" style="height: 100%">
                <el-col :span="8" style="min-height: 1px">
                </el-col>
                <el-col :span="2">
                    <el-button size="mini" @click="showAllMap">展示/收起全图</el-button>
                </el-col>
                <el-col :span="6">
                    <div style="min-width: 1px"></div>
                </el-col>
                <el-col :span="6">
                    <div style="min-width: 1px"></div>
                </el-col>
                <el-col :span="2">
                    <el-button size="mini" @click="backToMap">回退</el-button>
                </el-col>
            </el-row>
        </el-card>
        <div id="photo" style="height: 95%"></div>
    </div>
</template>

<script>
    import Grid from "ol/tilegrid/TileGrid";
    import proj4 from "proj4";
    import Projection from "ol/proj/Projection";
    import {addCoordinateTransforms, addProjection, default as proj, transform, getTransform} from "ol/proj";
    import Tile from "ol/layer/Tile";
    import XYZ from "ol/source/XYZ";
    import Map from "ol/Map";
    import View from "ol/View";
    import {defaults as defaultInteractions, DragRotateAndZoom} from "ol/interaction";
    import {toStringHDMS} from "ol/coordinate";
    import VectorSource from "ol/source/Vector"
    import VectorLayer from "ol/layer/Vector"
    import Polygon from "ol/geom/Polygon"
    import Feature from "ol/Feature"
    import {Style, Fill, Text, Stroke} from "ol/style"
    import Point from "ol/geom/Point";
    import 'ol/ol.css'

    export default {
        name: "soil-photo",
        data() {
            return {
                projection_32650: '',
                resolutions: [
                    4.2333418000169338,
                    2.1166709000084669,
                    1.0583354500042335,
                    0.52916772500211673,
                    0.264583862505836,
                    0.13229193125052918,
                    0.066145965625264591,
                    0.033072982812632296
                ],
                origin: [-5120900, 9998100],
                extent: [326903.42680000002, 4587828.3335700007, 327830.73451000004, 4588742.9504500004],
                line: [],
                coordinates: [],
                map: '',
                allMap: false
            }
        },
        mounted() {
            this.initMap();
            // this.addPosition();
        },
        methods: {
            initMap() {
                const _this = this;
                var tileGrid = new Grid({
                    tileSize: 256,
                    origin: _this.origin,
                    resolutions: _this.resolutions,
                    extent: _this.extent
                });
                proj4.defs('EPSG:32650', '+proj=utm +zone=50 +datum=WGS84 +units=m +no_defs');
                this.projection_32650 = new Projection({
                    code: 'EPSG:32650',
                    extent: [166021.44, 0.00, 534994.66, 9329005.18],
                    units: 'm'
                });
                addProjection(this.projection_32650);
                addCoordinateTransforms('EPSG:3857', 'EPSG:32650',
                    function (coordinate) {
                        return proj4('EPSG:3857', 'EPSG:32650', coordinate)
                    },
                    function (coordinate) {
                        return proj4('EPSG:32650', 'EPSG:3857', coordinate)
                    }
                );
                let photoLayer = new Tile({
                    source: new XYZ({
                        projection: _this.projection_32650,
                        tileGrid: tileGrid,
                        tileUrlFunction: function (tileCoord, pixelRatio, proj) {
                            var x, y, z;
                            // 瓦片行号
                            // console.log("-----------------------tileCoord---------------------------")
                            // console.log(tileCoord)
                            x = _this.zeroPad(tileCoord[1], 8, 16);
                            // 瓦片列号
                            // y =  _this.zeroPad(tileCoord[2] + 656661 * Math.pow(2, tileCoord[0]), 8, 16);
                            y = _this.zeroPad(tileCoord[2], 8, 16);
                            // 缩放级别
                            z = _this.zeroPad(tileCoord[0], 2, 10);
                            // console.log('find ok')
                            // console.log(y + '=yyy')
                            // console.log(z + '=zzz')
                            // console.log("in tileUrlFunction")
                            // console.log(' Z:' + x + ' x:' + y + ' y:' + z)
                            // return `a0714/a0714/_alllayers/L${z}/R${y}/C${x}.png`
                            return `https://gengyun-1304940588.cos.ap-nanjing.myqcloud.com/a0714/a0714/_alllayers/L${z}/R${y}/C${x}.png`
                            // return 'https://gengyun-1304940588.cos.ap-nanjing.myqcloud.com/webpack/a_demo/package.json'
                            // return '/_alllayers/L03/R0004e171/C000836d5.png';
                            // return '/satellite/1/1/0.jpg';
                        }
                        // url: '/satellite/1/1/0.jpg'
                    })

                });

                this.map = new Map({
                    layers: [
                        // rootLayer,
                        photoLayer
                    ],
                    view: new View({
                        center: transform([326912.42680000002, 4587835.3335700007], 'EPSG:32650', 'EPSG:3857'),
                        resolutions: _this.resolutions,
                        resolution: _this.resolutions[4],
                        minZoom: 3,
                        // extent: []
                    }),
                    interactions: defaultInteractions().extend([new DragRotateAndZoom()]),
                    target: 'photo'
                })

            },
            zeroPad(num, len, radix) {
                var str = num.toString(radix || 10);
                while (str.length < len) {
                    str = '0' + str
                }
                return str
            },
            addPosition() {
                const _this = this;
                this.map.addEventListener('click', function (evt) {
                    var coordinate = evt.coordinate;
                    // console.log(coordinate)
                    _this.coordinates[_this.coordinates.length] = coordinate;
                    var hdms = toStringHDMS(transform(
                        coordinate, 'EPSG:3857', 'EPSG:4326'));
                    _this.line[_this.line.length] = transform(
                        coordinate, 'EPSG:3857', 'EPSG:4326')
                    console.log(_this.line)
                    // overlay.setPosition(coordinate);
                    // map.addOverlay(overlay);
                });
            },
            makeLine() {
                const polygon = new Polygon([this.line]);
                polygon.applyTransform(getTransform('EPSG:4326', 'EPSG:3857'));
                var feature = new Feature(polygon);

                var vectorSource = new VectorSource();
                vectorSource.addFeature(feature);

                var vectorLayer = new VectorLayer({
                    source: vectorSource
                });
                this.map.addLayer(vectorLayer);
                this.addText();
                // this.getCenter()
            },
            addText() {
                let itemStyle = new Style({
                    text: new Text(({
                        // 位置
                        textAlign: 'center',
                        // 基准线
                        textBaseline: 'middle',
                        // 文字样式
                        font: 'bold 12px 微软雅黑',
                        // 文本内容
                        text: '我是文字',
                        // 文字颜色
                        fill: new Fill({color: '#587de5'}),
                        // 文字背景
                        stroke: new Stroke({color: '#ffcc33', width: 10})
                    }))
                });
                const position = this.getCenter();
                let featureItem = new Feature({
                    geometry: new Point(transform([position.middleLon, position.middleLat], 'EPSG:4326', 'EPSG:3857')),
                });
                // console.log(new Point(transform([326912.42680000002, 4587835.3335700007], 'EPSG:32650', 'EPSG:3857'))
                featureItem.setStyle(itemStyle);
                let vectorSource = new VectorSource({});
                vectorSource.addFeature(featureItem);
                let vectorLayer = new VectorLayer({
                    source: vectorSource
                });
                this.map.addLayer(vectorLayer)
            },
            getCenter() {
                const line = this.line;
                const lineLength = line.length;
                let maxLat = -1;
                let minLat = 10000;
                let maxLon = -1;
                let minLon = 10000;
                for (let i = 0; i < lineLength; i++) {
                    if (line[i][0] < minLon) {
                        minLon = line[i][0]
                    }
                    if (line[i][0] > maxLon) {
                        maxLon = line[i][0]
                    }
                    if (line[i][1] < minLat) {
                        minLat = line[i][1]
                    }
                    if (line[i][1] > maxLat) {
                        maxLat = line[i][1]
                    }
                }
                const middleLat = (maxLat + minLat) / 2;
                const middleLon = (maxLon + minLon) / 2;
                console.log("middleLat = " + middleLat + " middleLon = " + middleLon)
                return {middleLon, middleLat}

            },
            backToMap() {
                // console.log(this.map.getView().getZoom())
                // console.log(this.$parent);
                this.$parent.changeToMap()
            },
            showAllMap() {
                if (this.allMap) {
                    document.getElementById('side_bar').style.width = 0 + '%'
                    this.allMap = !this.allMap
                } else {
                    document.getElementById('side_bar').style.width = 30 + '%'
                    this.allMap = !this.allMap


                }
            }
        }
    }
</script>

<style scoped>

</style>